<?php

class IPAddressChecking{
	var $ip_address;

	function IPAddressChecking($address=''){
		$this->ip_address=$address;
		$ar = array($this->ip_address);
	}
    
//	function checkIPorRange(){
//		if (ereg("-",$this->ip_address)) {
//			$ar = explode("-",$this->ip_address);
//
//			$your_long_ip = ip2long($_SERVER["REMOTE_ADDR"]);
//			if (($your_long_ip >= ip2long($ar[0])) && ($your_long_ip <= ip2long($ar[1]))) {
//				return true;
//			}
//		} else {
//			if ($_SERVER["REMOTE_ADDR"] == $this->ip_address) {
//				return true;
//			}
//		}
//		return false;
//	}

}

function check_blocked_ip(){
	global $db;
	$sql = 'SELECT id_ip_address, ip_address 
	FROM gain_allowed_ip
	WHERE removed IS null';
	$rsl = $db->GetAssoc($sql);
	
	$sql = 'SELECT id_ip_address, ip_address 
	FROM gain_disallowed_ip
	WHERE removed IS null';
	$dis = $db->GetAssoc($sql);

	if ($rsl) {
		if ($dis) {
			if (in_array ($_SERVER["REMOTE_ADDR"],$dis)){
				return false;
			}
		}
		if (in_array ($_SERVER["REMOTE_ADDR"],$rsl)){
			return true;
		} else {
			foreach($rsl as $ip) {
          		if($ip=='*'){
          			return true;
          		} elseif(preg_match('!'.$ip.'!Uis',$_SERVER['REMOTE_ADDR'])) {
               		return true;
          		}
    		}
		}
	
	}
	return false;
}

function check_blocked_account($user){
	global $db;
	$sql = SQL('SELECT status FROM '.PREFIX.'sec_blocked_account WHERE user=%s AND unblock_time>%d',$user,time());
	$rsl = $db->GetOne($sql);
	if ($rsl) {
		return false;
	} else {
		return true;
	}
}

function check_multi_session($id_user, $max_sess_number){
	global $db;
	if (empty($max_sess_number)) {
		$max_sess_number = 1;
	}
	$sql = SQL('SELECT count(*) AS sess_number FROM '.PREFIX.'sec_session WHERE id_user=%d AND expire>'.time().' AND ip != %s', $id_user, $_SERVER['REMOTE_ADDR']);
	$rsl = $db->GetRow($sql);
	if ($rsl['sess_number'] >= $max_sess_number) {
		return false;
	}
	return true;
}

/**
 * check to add blocked account
 *
 * @return boolean true (blocked)
 * @param string $user login
 * @param int $try time to try login with wrong password
 * @param int $within_time wrong within time limits (sec)
 * @param int $blocked_time blocked time (sec)
 */
function blocked_account($user,$try,$within_time,$blocked_time){
	global $db;
	$sql = SQL('SELECT time FROM '.PREFIX.'sec_access_log WHERE type="password" AND user=%s ORDER BY time DESC LIMIT 0,%d',$user,$try);
	$rsl = $db->GetCol($sql);
	if ($rsl) {
		if (count($rsl) == $try) {
			$period = $rsl[0] - $rsl[$try-1];
			if ($period < $within_time) {
				$sql = SQL('SELECT status FROM '.PREFIX.'sec_blocked_account WHERE user=%s',$user);
				if ($db->GetOne($sql)) {
					$status = 'double blocked';
					$blocked_time *= 2;
				} else {
					$status = 'blocked';
				}
				$sql = SQL('INSERT INTO '.PREFIX.'sec_blocked_account(user,status,unblock_time,created) VALUES(%s,%s,%d,%d)',$user,$status,strtotime('+'.$blocked_time.' seconds'),time());
				if ($db->Execute($sql)) {
					return true;
				}
			}
		}
	}
	return false;
}

function user_log($user='', $type=''){
	global $db;
	$user = trim($user);
	$ip = $_SERVER['REMOTE_ADDR'];
	$time = time();
	$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
	$country_name = substr($hostname,strrpos($hostname,".")+1);
	if (strstr($hostname,'.') && ereg('[A-Za-z]+', $country_name)) {
		$country_name_display = '('.$country_name.')';
	} else {
		$country_name = '';
		$country_name_display = '';
	}
	switch($type) {
		case 'login':
			$message = 'User '.$user.' logged in';
			break;
		case 'logout':
			$message = 'User '.$user.' logged out';
			break;
		case 'user':
			$message = 'User '.$user.' not exist but try to access';
			break;
		case 'password':
			$message = 'Credentials incorrect: user '.$user;
			break;
		case 'ip_blocked':
			$message = 'IP was blocked: user '.$user;
			break;
	}
	$sql = 'INSERT INTO '.PREFIX.'sec_access_log (ip, country_name, time, user, type, message) VALUES("'.$ip.'", "'.$country_name.'", '.$time.', "'.$user.'", "'.$type.'", "'.$message.'")';
	return $db->Execute($sql);
}

function get_user_session(){
	global $db;
	$sql = 'SELECT id, id_user, username, ip, hostname, expire, url, url_name, session_lifetime FROM '.PREFIX.'sec_session WHERE expire>'.time().' ORDER BY expire DESC';
	$rsl = $db->GetAssoc($sql);
	if ($rsl) {
		foreach ($rsl as $k => $v) {
			$session_data[$k] = $v;
		}
	}
	return $session_data;
}

function delete_user_session($id_sess){
	global $db;
	#user terminate by self
	$sql = SQL('SELECT COUNT(id) FROM '.PREFIX.'sec_session WHERE id=%d AND session_id=%s', $id_sess, session_id());
	$curr = $db->GetOne($sql);
	if ($curr > 0) {
		return false;
	}

	$sql = SQL('UPDATE '.PREFIX.'sec_session SET expire='.time().' WHERE id=%d', $id_sess);
	$db->Execute($sql);
	return true;
}

function get_user_log($where='',$page_link_search=''){
	global $db;
	$per_page = 20;
	$limit = ' LIMIT '.((int)$_REQUEST['user_log']['page']*$per_page).','.$per_page;
	$sql = 'SELECT COUNT(*) FROM '.PREFIX.'sec_access_log '.$where;
	$record_num = $db->GetOne($sql);

	$sql = 'SELECT id, ip, time, message, type FROM '.PREFIX.'sec_access_log '.$where.' ORDER BY time DESC'.$limit;
	$rsl = $db->GetAssoc($sql);
	#get page link
	if ($_REQUEST['mod']) {
		$page_link .= 'mod='.$_REQUEST['mod'];
	}
	if ($_REQUEST['view']) {
		$page_link .= '&view='.$_REQUEST['view'];
	}

	if (!$_REQUEST['user_log']['page']) {
		$page_link .= '&user_log[page]='.$_REQUEST['user_log']['page'];
	}

	if ($page_link_search) {
		$page_link .= $page_link_search;
	}
	$paged_result = '<div>'.fw_paged_results_js('Pages: ','user_log',$record_num,$page_link,$per_page,'div#log_table_content').'</div>';

	return array('result' => $rsl,'paged' => $paged_result);
}
